package ignoreruleoperationlogic

import (
	"context"

	"dfx_cmdb/cmdb-blacklist-rpc/internal/svc"
	cmdb_blacklist_rpc "dfx_cmdb/cmdb-blacklist-rpc/types/cmdb-blacklist-rpc"
	cmdbblacklist "dfx_cmdb/models/cmdb-blacklist"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateIgnoreRuleLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateIgnoreRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateIgnoreRuleLogic {
	return &UpdateIgnoreRuleLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 修改忽略规则
func (l *UpdateIgnoreRuleLogic) UpdateIgnoreRule(in *cmdb_blacklist_rpc.UpdateIgnoreRuleRequest) (*cmdb_blacklist_rpc.PublicResponse, error) {
	// 参数验证
	if in.Id <= 0 {
		return &cmdb_blacklist_rpc.PublicResponse{
			Message: "id 必须大于0",
		}, nil
	}

	// 检查规则是否存在
	var existingRule cmdbblacklist.BlacklistIgnoreRule
	if err := l.svcCtx.PDB.First(&existingRule, in.Id).Error; err != nil {
		l.Errorf("查询忽略规则失败: %v", err)
		return &cmdb_blacklist_rpc.PublicResponse{
			Message: "忽略规则不存在",
		}, nil
	}

	// 构建更新数据
	updateData := make(map[string]interface{})

	if in.IgnoreType != "" {
		updateData["ignore_type"] = in.IgnoreType
	}
	if in.IgnoreVal != "" {
		updateData["ignore_val"] = in.IgnoreVal
	}
	// bool 类型默认为 false，我们总是更新它
	updateData["enable"] = in.Enabled

	// 如果没有需要更新的字段
	if len(updateData) == 0 {
		return &cmdb_blacklist_rpc.PublicResponse{
			Message: "没有需要更新的字段",
		}, nil
	}

	// 如果更新了 ignore_type 或 ignore_val，需要检查是否有重复
	if _, hasType := updateData["ignore_type"]; hasType {
		if _, hasVal := updateData["ignore_val"]; hasVal {
			var duplicateRule cmdbblacklist.BlacklistIgnoreRule
			ignoreType := updateData["ignore_type"].(string)
			ignoreVal := updateData["ignore_val"].(string)
			err := l.svcCtx.PDB.Where("ignore_type = ? AND ignore_val = ? AND id != ?",
				ignoreType, ignoreVal, in.Id).
				First(&duplicateRule).Error
			if err == nil {
				return &cmdb_blacklist_rpc.PublicResponse{
					Message: "该忽略规则已存在",
				}, nil
			}
		}
	}

	// 执行更新
	if err := l.svcCtx.PDB.Model(&existingRule).Updates(updateData).Error; err != nil {
		l.Errorf("更新忽略规则失败: %v", err)
		return &cmdb_blacklist_rpc.PublicResponse{
			Message: "更新忽略规则失败",
		}, err
	}

	return &cmdb_blacklist_rpc.PublicResponse{
		Message: "更新忽略规则成功",
	}, nil
}
